package seg.tef4.whms.util.datastore;

import android.content.Context;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;

/**
 * 文件读写封装类
 */
public class FileHelper {
    /**
     * 写文件
     * @param context
     * @param fileName
     * @param content
     */
    public  void fileWrite(Context context, String fileName, String content){
        try {
            FileOutputStream fileOutputStream = context.openFileOutput(fileName,Context.MODE_APPEND);
            OutputStreamWriter  outputStreamWriter = new OutputStreamWriter(fileOutputStream);
            BufferedWriter writer = new BufferedWriter(outputStreamWriter);
            writer.write(content);
            fileOutputStream.close();
            outputStreamWriter.close();
            writer.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 读文件内容
     * @param context
     * @param fileName
     * @return
     */
    public  ArrayList<String> fileReader(Context context, String fileName){
        try {
            FileInputStream fileInputStream = context.openFileInput(fileName);
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            ArrayList<String> result = new ArrayList<>();
            String tempLine;
            while ((tempLine = bufferedReader.readLine()) !=null){
                result.add(tempLine);
            }
            fileInputStream.close();
            inputStreamReader.close();
            bufferedReader.close();
            return result;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
